package com.fingard.dsp.bank.directbank.srcb01;

import com.fingard.FGBiz;
import com.fingard.constant.DateFormat2;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class SRCB01Transaction extends SRCB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();    //写返回ATS的统一头部信息

        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            String queryAct = p_req7516.actNum;
            boolean queryFlag = true;
            int currentCount = 1;
            while (queryFlag) {
                String[] loginResult = login();
                if (loginResult[0].length() != 0) {
                    if (!retAts.hasWrittenRespCode) {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(loginResult[1]);
                    }
                }
                //新建发送银行报文
                XmlTextWriter xmlWriterStep1 = new XmlTextWriter();
                String transCode = getBankConfig().getMapValueByKey("transCode", "7516");
                writeCommonHeader(xmlWriterStep1, transCode, "");
                List<String[]> paramStep1 = new ArrayList<String[]>();
                paramStep1.add(new String[]{"AcctNo", queryAct});   //账号
                paramStep1.add(new String[]{"AcctCurr", getBankConfig().getMapValueByKey("currencyMapping", p_req7516.actCur)});
                paramStep1.add(new String[]{"StartDate", p_req7516.dateFrom});
                paramStep1.add(new String[]{"EndDate", p_req7516.dateTo});
                paramStep1.add(new String[]{"CurrentCount", String.valueOf(currentCount)});
                paramStep1.add(new String[]{"version", "2"});
                writeBodyParams(xmlWriterStep1, paramStep1);
                String[] result = sendToBank(xmlWriterStep1.toXmlString());
                if (result[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(result[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/response/head/ret_code");
                        Integer totalCount = Integer.parseInt(tmpBkReader.getFirstText("/response/body/total_count"));
                        if (totalCount < 10 || currentCount + 10 > totalCount) {
                            queryFlag = false;
                        }
                        if ("000000".equals(tmpRetCode)) {
                            while (tmpBkReader.read("/response/body/tran_record_list/record")) {
                                if (!retAts.hasWrittenRespCode) {
                                    retAts.writeRespCode("0");
                                    retAts.writeRespInfo("success");
                                }
                                RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                tmpRetDetail.actNum = p_req7516.actNum;     //银行账号
                                tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("payee_account_no");      //收款人账号
                                tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("payee_account_name");   //收款人名称
                                tmpRetDetail.recAccBank = "";   //对方开户银行
                                String tranDate = tmpBkReader.readedXElement.getSingleText("tran_date");    //交易日期  YYYYMMDD
                                String tranTime = tmpBkReader.readedXElement.getSingleText("tran_date");    //交易时间  hhmmss
                                Date transDateTime = new DateFormat2("YYYYMMDDhhmmss").parse(tranDate + tranTime);
                                tmpRetDetail.tranDate = Format.Date10Format.format(transDateTime);      //交易日期 yyyy-MM-dd
                                tmpRetDetail.tranTime = Format.DateTimeFormat.format(transDateTime);    //交易时间 yyyy-MM-dd HH:mm:ss
                                tmpRetDetail.tranAmt = tmpBkReader.readedXElement.getSingleText("tran_amount"); //交易金额
                                tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("balance");  //帐户余额
                                String cdFlag = tmpBkReader.readedXElement.getSingleText("cd_flag");  //0 - 借  1 - 贷
                                tmpRetDetail.cdFlag = cdFlag.equals("1") ? "0" : "1";
                                String payUsage = tmpBkReader.readedXElement.getSingleText("pay_usage"); //用途
                                if (payUsage.contains("+")) {
                                    tmpRetDetail.usage = payUsage.substring(0, payUsage.lastIndexOf("+"));
                                    tmpRetDetail.abstr = payUsage.substring(payUsage.lastIndexOf("+") + 1, payUsage.length());
                                } else {
                                    tmpRetDetail.usage = payUsage;
                                }
                                tmpRetDetail.payCode = tmpRetDetail.usage;
                                tmpRetDetail.cur = getBankConfig().getMapKeyByValue("currencyMapping", "acct_curr");    //币种
                                tmpRetDetail.askNumber = tmpBkReader.readedXElement.getSingleText("core_Serial_Num");
                                tmpRetDetail.originator = tmpBkReader.readedXElement.getSingleText("core_Serial_Num");
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmpBkReader.getFirstText("/response/head/err_msg"));
                        }
                    } else {
                        WriteBankLogLn("步骤一发送成功，银行返回报文解析失败，报文内容为：" + result[1]);
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(result[1]);
                    }
                }
                currentCount += 10;
            }
        } catch (Exception e) {
            FGBiz.limitMsg.exception(reqHeader.bankCode, e);
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            WriteBankLogLn(e);
        }

        if ("-1".equals(tmpRespCode)) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        tmpReq7516.higherLevelAct = p_req7515.higherLevelAct;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;//设置开始时间和结束时间都为当天
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
